/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package client;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 *
 * @author buyandalai
 */
public class client extends Thread {
    private InputStream sin;
    private OutputStream sout;
    private DataInputStream in;
    private DataOutputStream out;
    private BufferedReader keyboard;
    private Socket socket;
    private InetAddress ipAddress;
    private String line;
    private String username;
    private String password;
    clientWindow cw;

    public client(clientWindow cw){
        this.cw = cw;
    }


    public void sendMessage(String msg)
    {
        try {
            out.writeUTF(msg);
            out.flush();
        } catch (IOException ex) {
            Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void run()
    {
        try{
            ipAddress = InetAddress.getByName(cw.getIpAddress()); // gets an object representing ip
            socket = new Socket(ipAddress, cw.getPort()); // connects to the socket
            cw.connected();
            sin = socket.getInputStream();
            sout = socket.getOutputStream();
            in = new DataInputStream(sin);
            out = new DataOutputStream(sout);
            keyboard = new BufferedReader(new InputStreamReader(System.in));



            while(true){
                line = in.readUTF();
                cw.serverReply(line);
            }
        }
        catch (UnknownHostException ex) {
            ex.printStackTrace();
        }catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void close()
    {
        try {
            socket.close();
        } catch (IOException ex) {
            Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
